package fire.and.near.challenger;

import fire.and.near.challenger.R;
import fire.and.near.challenger.database.ProfileManager;
import fire.and.near.challenger.web.HttpRequestSender;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class UserDetailsActivity extends Activity {
	
	private ProfileManager  mProfileManager 	= null;
	private EditText		mEditTextUsername 	= null;
	private EditText		mEditTextPassword 	= null;
	private String			mUsernameCache		= null;
	private String			mPasswordCache		= null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_user_details);
		
		mProfileManager = new ProfileManager(this);
		
		mEditTextUsername = (EditText)findViewById(R.id.editText_username_details);
		mEditTextPassword = (EditText)findViewById(R.id.editText_password_details);
		
		mUsernameCache = mProfileManager.getUsername();
		mPasswordCache = mProfileManager.getPassword();
		
		mEditTextUsername.setText(mUsernameCache);
		mEditTextPassword.setText(mPasswordCache);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_logout) {
			if (HttpRequestSender.isNetworkAvailable(this)) {
				LoginActivity.mFbHelper.logout();
			}

			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void applyChanges(View v) {
		String newUsername = mEditTextUsername.getText().toString().trim();
		String newPassword = mEditTextPassword.getText().toString().trim();
		
		if (newUsername.length() == 0) {
			Toast.makeText(this, "Username CAN NOT be empty", Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (newPassword.length() == 0) {
			Toast.makeText(this, "Password CAN NOT be empty", Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (!newUsername.equals(mUsernameCache)) {
			mProfileManager.setUsername(newUsername);
		}
		
		if (!newPassword.equals(mPasswordCache)) {
			mProfileManager.setPassword(newPassword);
		}
		
		Toast.makeText(this, "Updated!", Toast.LENGTH_SHORT).show();
		
		finish();
	}
	
	public void cancelChanges(View v) {
		finish();
	}
}
